import twitter
from pytify import Spotify
import urllib, sys

class TwitMySpotify(object):
    username = 'username'
    password = 'password'
    
    def __init__(self):
        try:
            self.spotify = Spotify()
        except:
            raise self.SpotifyNotRunningException()
        try:
            self.twitterapi = twitter.Api(username = self.username, password = self.password) 
            
        except:
            raise self.CouldNotTalkToTwitterException()
        
    def _getTrack(self):
        currentTrack = self.spotify.getCurrentTrack()         
        #return unicode(currentTrack, errors='xmlcharrefreplace').encode('utf-8')
        return currentTrack

    def _getArtist(self):        
        currentArtist = self.spotify.getCurrentArtist()         
        #return unicode(currentArtist, errors='xmlcharrefreplace').encode('utf-8')
        return currentArtist
    
    def _getTrackListing(self):
        currentTrack = self._getTrack()
        currentArtist = self._getArtist()  
        track_listing = currentArtist+' '+currentTrack
        return  track_listing
    
    def twit(self):
        twit_string = 'Listening to '
        track_listing = self._getTrackListing() 
        link_string = urllib.quote(track_listing)
        link_string = 'http://open.spotify.com/search/'+link_string  
        twit_string = twit_string + unicode(track_listing, errors='replace').encode('utf-8') + ' '+link_string        
        if len(twit_string)>=140:
            twit_string = 'Listening to '
            link_string = urllib.quote(self._getArtist())
            link_string = 'http://open.spotify.com/search/'+link_string 
            twit_string = twit_string + unicode(self._getArtist(), errors='replace').encode('utf-8') + ' '+link_string        
        status = self.twitterapi.PostUpdate(twit_string)  
        return  status.text
    
             
    class SpotifyNotRunningException:
        def __str__(self):
            return "Spotify window not found. Is Spotify really running?" 
    class CouldNotTalkToTwitterException:
        def __str__(self):
            return "Couldn't talk to twitter - are you username and password correct?"  
         
COMMANDLINE_COMMANDS = {
        'twit': TwitMySpotify.twit,        
}
      
if __name__ == "__main__":
    def fail():
        print "Usage: TwitMySpotify.py "+"|".join(COMMANDLINE_COMMANDS.keys())
        sys.exit(0)

    if len(sys.argv) < 2: fail()

    cmd_name = sys.argv[1]
    if not COMMANDLINE_COMMANDS.has_key(cmd_name): fail()

    cmd = COMMANDLINE_COMMANDS[cmd_name]
    twitmyspotify = TwitMySpotify()
    res = cmd(twitmyspotify)
    
    if res: print res